import { useRef, useCallback, useEffect, DOMElement } from 'react';
import { debounce } from 'lodash';

const echarts = require('echarts/lib/echarts');

/**
 * 提供 mount 回调，如果是初次，则 echarts.init 并将结果返回到 ref.current
 * 记录到 ref.current 下
 */
export function useEchart(theme: any) {
  const refChart = useRef();
  const onChartMount = useCallback(domChart => {
    if (refChart.current) return;
    refChart.current = echarts.init(domChart, theme);
  }, []);
  useEffect(() => {
    if (!refChart.current) return;
    const handleResize = debounce(() => refChart.current.resize(), 200);
    global.window.addEventListener('resize', handleResize);
    return () => {
      global.window.removeEventListener('resize', handleResize);
    };
  }, []);
  return [refChart, onChartMount];
}

export default useEchart;
